package com.sx.iptv.http;

import com.alibaba.fastjson.util.IOUtils;
import com.sx.iptv.model.Param;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OkHttpExample {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpExample.class);

    public static Param getParam() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("http://toutiao.cnwest.com/static/v1/stream.js")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                logger.info("Response: {}", responseBody);

                Pattern sTV = Pattern.compile("var\\s+sTV\\s*=\\s*\"([^\"]*)\";");
                Pattern sRadio = Pattern.compile("var\\s+sRadio\\s*=\\s*\"([^\"]*)\";");

                Param build = Param.builder().build();

                Matcher matcher = sTV.matcher(responseBody);
                if (matcher.find()) {
                    String sTvValue = matcher.group(1);
                    build.setSTV(sTvValue);
                    logger.info("sTV: {}", sTvValue);
                }

                matcher = sRadio.matcher(responseBody);
                if (matcher.find()) {
                    String sRadioValue = matcher.group(1);
                    build.setSRadio(sRadioValue);
                    logger.info("sRadio: {}", sRadioValue);
                }
                return build;
            } else {
                logger.info("Request failed: {}", response.code());
                return null;
            }
        } catch (IOException e) {
            logger.error("服务请求异常!");
            logger.error(e.getLocalizedMessage(), e);
            return null;
        } finally {
            IOUtils.close(response);
        }
    }

    public static void main(String[] args) {
        getParam();
    }
}
